package com.wis.traffic.common.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class HttpUtil {
	// 日志
//	private static Logger _log = LoggerFactory.getLogger(HttpUtil.class);
		
	public static Object get(URI uri,String respType) {
        Object reObj = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpEntity entity;
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(uri);

            httpResponse = httpClient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                entity = httpResponse.getEntity();
                if (entity != null) {
                    entity = new BufferedHttpEntity(entity);
                    reObj = getReObjFromResponse(entity, Charset.forName("UTF-8"), respType);
                }
            }else if (httpResponse.getStatusLine().getStatusCode() == 204) {
//            	_log.debug("the response with no return value. which path is :"
//                        + uri.toURL().toString());
            }else{
                throw new RuntimeException("Failed : HTTP error code : "
                        + httpResponse.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
//        	_log.error(e.getMessage());
        } finally {
            if (httpResponse != null)
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (httpClient != null)
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return reObj;
    }
	
	public static Object getReObjFromResponse(HttpEntity entity, Charset defaultCharset2, String respType) {
        Object reObj = null;
        if("RESPONSE_STR".equals(respType)){
            try {
                reObj = EntityUtils.toString(entity, defaultCharset2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return reObj;
    }
}
